package com.gz.moreaseManager.config;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.gz.moreaseManager.sys.entity.Role;
import com.gz.moreaseManager.sys.entity.User;
import com.gz.moreaseManager.sys.service.IRoleService;
import com.gz.moreaseManager.sys.service.IUserRoleService;
import com.gz.moreaseManager.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户认证服务
 */
@Component
public class SelfUserDetailsService implements UserDetailsService {

	private final IUserService userService;
	private final IUserRoleService userRoleService;

	@Autowired
	public SelfUserDetailsService(IUserService userService,IUserRoleService userRoleService) {

		this.userService = userService;
		this.userRoleService = userRoleService;
	}

	/**
	 * 查询用户信息和权限
	 *
	 * @param userName 用户名
	 * @return 用户信息和权限
	 */
	@Override
	public UserDetails loadUserByUsername(String userName) {
		User sysUser = userService.selectOne( new EntityWrapper<User>()
				.eq("user_name",userName)
				.or().eq("user_phone",userName));
		if (sysUser == null)
			throw new UsernameNotFoundException(String.format("用户'%s'不存在", userName));
		else if (sysUser.getStatus() != 1)
			throw new DisabledException("用户已被禁用");
		/*throw new AccountExpiredException("账号已过期");
		throw new LockedException("账号已被锁定");
		throw new LockedException("凭证已过期");*/
		List<Role> roleList = userRoleService.findRoleListByUserId( sysUser.getUserId() );
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		for (Role roleInfo : roleList) {
			if (roleInfo != null && roleInfo.getRoleName() != null) {
				grantedAuthorities.add(new SimpleGrantedAuthority(roleInfo.getRoleName()));
			}
		}
		SelfUserDetails userDetails = new SelfUserDetails();
		userDetails.setUserId(sysUser.getUserId());
		userDetails.setUsername(sysUser.getUserName());
		userDetails.setPassword(sysUser.getPassword());
		userDetails.setPortrait(sysUser.getPortrait());
		userDetails.setUserAlias(sysUser.getUserAlias());
		userDetails.setUserEmail(sysUser.getUserEmail());
		userDetails.setUserPhone(sysUser.getUserPhone());
		userDetails.setAuthorities(grantedAuthorities);
		return userDetails;
	}
}